package com.cloudea.lotus.dao;

import org.apache.commons.dbcp2.*;
import org.apache.commons.pool2.ObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.log4j.Logger;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class MySQLConnector implements Connector {
    private Logger logger = Logger.getLogger(this.getClass());
    private  String uri = "jdbc:mysql://%s/%s?user=%s&password=%s&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&";

    DataSource dataSource = null;

    public MySQLConnector(MySQLConfig mySQLConfig) {
        //创建数据库连接池
        try {
            logger.info("正在创建数据库连接池");
            //Class.forName("com.mysql.jdbc.Driver");
            Class.forName("com.mysql.cj.jdbc.Driver");
            dataSource = setupDataSource(String.format(uri,
                    mySQLConfig.getDbPath(),
                    mySQLConfig.getDbName(),
                    mySQLConfig.getDbUser(),
                    mySQLConfig.getDbPass()));
            logger.info("成功创建数据库连接池");
        } catch (ClassNotFoundException e) {
            logger.error("无法连接数据库", e);
            System.exit(-1);
        }
    }

    @Override
    public Connection connect() throws SQLException {
        return dataSource.getConnection();
    }

    private static DataSource setupDataSource(String connectURI) {
        ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI,null);
        PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null);
        ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory);
        poolableConnectionFactory.setPool(connectionPool);
        PoolingDataSource<PoolableConnection> dataSource =new PoolingDataSource<>(connectionPool);
        return dataSource;
    }
}
